<?php
/**
 * 用户登录相关
 *
 * @package util
 * @author wangzhiliang
 */

class User
{
    # Cookie Key
    const COOKIE_KEY = 'SDUSER';
    # 用户登录状态Key
    const COOKIE_CAS_LOGIN_STAT = 'CAS_LOGIN_STATE';
    # CAS 登录接口地址
    const CAS_HOSTNAME = 'https://cas.sdo.com';
    /**
     * 解析用户信息
     * 
     * @param string $content
     * @return string||false 
     */
    public static function parseUserName ($content)
    {
        $userInfo = explode("\n", $content);
        if (isset($userInfo[0]) && $userInfo[0] === 'yes') {
            $user = '';
            $user .= $userInfo[1] . '||';
            $user .= $userInfo[2] . '||';
            $user .= $userInfo[3];
            return iconv('gb2312', 'utf-8', $user);
        } else {
            return FALSE;
        }
    }
    /**
     * 设置用户信息
     * 
     * @param string $content
     * @return string
     */
    public static function setAuthInfo ($content)
    {
        $user = self::parseUserName($content);
        require_once dirname(__FILE__) . '/../mcrypt/MCrypt.php';
        $userInfo = base64_encode(MCrypt::tripleDESEncrypt($user));
        setcookie(self::COOKIE_KEY, $userInfo, 0, '/','snda.com');
        return $userInfo;
    }
    /**
     * 获取用户信息
     * 
     * @param string $userInfo
     * @return array||false
     */
    public static function getAuthInfo ($userInfo = false)
    {
    	/*
    	# 其他应用推出，同步退出
        if (! isset($_COOKIE[self::COOKIE_CAS_LOGIN_STAT])) {
            self::delAuthInfo();
            return FALSE;
        }*/
        # 第一次未写入Cookie支持赋值
        if ($userInfo) {
            $_COOKIE[self::COOKIE_KEY] = $userInfo;
        }
        if (isset($_COOKIE[self::COOKIE_KEY]) && $_COOKIE[self::COOKIE_KEY]) {
            static $ret = NULL;
            if ($ret === NULL) {
                require_once dirname(__FILE__) . '/../mcrypt/MCrypt.php';
                $user = MCrypt::tripleDESDecrypt(base64_decode($_COOKIE[self::COOKIE_KEY]));
                $userInfo = explode('||', $user);
                if (count($userInfo) == 3) {    
                    list ($ret['ptid'], $ret['sdid'], $ret['originid']) = $userInfo;
                    return $ret;
                } else {
                    return $ret = FALSE;
                }
            } else {
                return $ret;
            }
        } else {
            # 初次访问应用，判断统一认证状态
            return self::_validate();
        }
    }
    /**
     * 静态获取用户信息
     *
     * @param string $type in array('ptid' , 'sdid' , 'originid')
     * @return string|false
     */
    public static function getUserInfo ($type)
    {
        if (! in_array($type, array(
            'ptid' , 
            'sdid' , 
            'originid'
        ))) {
            return FALSE;
        }
        $ret = self::getAuthInfo();
        if (isset($ret[$type])) {
            return $ret[$type];
        } else {
            return FALSE;
        }
    }
    /**
     * SSO login
     *
     * @param string $url
     */
    public static function SSOLogin ($url = NULL, $return = FALSE)
    {
        # 重定向URL
        if ($url !== NULL) {
            $redirectURL = $url;
        } else {
            $redirectURL = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        }
        $delimiters = (strpos($redirectURL, '?') === FALSE) ? '?' : '&';
        $casURL = self::CAS_HOSTNAME . '/cas/login?service=' . urlencode($redirectURL . $delimiters . 'url=' . urlencode($redirectURL));
        
        if ($return) {
            return $casURL;
        }
        setcookie(self::COOKIE_CAS_LOGIN_STAT,'1', 0, '/','snda.com');
        require_once dirname(__FILE__) . '/../http/Response.php';
        Response::redirect($casURL);
    }
    /**
     * SSO login
     *
     * @param string $url
     */
    public static function SSOLogout ($url = NULL, $return = FALSE)
    {
        # 重定向URL
        if ($url !== NULL) {
            $redirectURL = $url;
        } else {
            $redirectURL = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        }
        $casURL = self::CAS_HOSTNAME . '/cas/logout?url=' . urlencode($redirectURL);
        if ($return) {
            return $casURL;
        }
        # 清除Cookie
        self::delAuthInfo();
        require_once dirname(__FILE__) . '/../http/Response.php';
        Response::redirect($casURL);
    }
    /**
     * 验证用户信息
     *
     * @return array||false  用户信息或false
     */
    private function _validate ()
    {
        # 重定向URL
        $redirectURL = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        # 存在 ticket
        if (isset($_GET['ticket']) && $_GET['ticket']) {
            $authenURL = self::CAS_HOSTNAME . '/cas/Validate?service=' . urlencode($redirectURL) . "&ticket={$_GET['ticket']}" . "&extend=true";
            require_once dirname(__FILE__) . '/../http/Request.php';
            $message = '';
            $content = Request::getContent($authenURL, $message, 'https');
            if ($content === FALSE) {
                # 出错
                return FALSE;
            } else {
                # 正常
                $content = self::setAuthInfo($content);
                if (isset($_GET['url'])) {
                    require_once dirname(__FILE__) . '/../http/Response.php';
                    Response::redirect($_GET['url']);
                }
                return self::getAuthInfo($content);
            }
        }
        # sdo Cookie 存在登录状态
        /*
        if (isset($_COOKIE[self::COOKIE_CAS_LOGIN_STAT]) && $_COOKIE[self::COOKIE_CAS_LOGIN_STAT] == 1) {
            $delimiters = (strpos($redirectURL, '?') === FALSE) ? '?' : '&';
            $casURL = self::CAS_HOSTNAME . '/cas/login?gateway=ture&service=' . urlencode($redirectURL . $delimiters . 'url=' . urlencode($redirectURL));
            require_once dirname(__FILE__) . '/../http/Response.php';
            Response::redirect($casURL);
        }*/
        return FALSE;
    }
    /**
     * 删除用户信息
     *
     */
    public static function delAuthInfo ()
    {
        setcookie(self::COOKIE_KEY, FALSE, 0, '/','snda.com');
        setcookie(self::COOKIE_CAS_LOGIN_STAT,0,time()-3600, '/','snda.com');
    }
    /**
     * 验证用户身份
     *
     * @param string $ptid		PTID
     * @param string $password	密码
     * @return array||false		array('code' => $code , 'info' => $info)
     */
    public static function verifyPassword ($ptid, $password)
    {
        $verifyURL = "http://ptcom.sdo.com/validate/ValidateStaticPassword.aspx?ptid={$ptid}&pwd={$password}";
        require_once dirname(__FILE__) . '/../http/Request.php';
        $message = '';
        $content = Request::getContent($verifyURL, $message);
        if ($content === FALSE) {
            # 出错
            return FALSE;
        } else {
            # 正常
            @list ($code, $info) = explode('^$^', $content);
            if ($code === '0') {
                $info = '验证成功';
            }
            return array(
                'code' => $code , 
                'info' => $info
            );
        }
    }
    /**
     * 帐号转换
     * $ret[0] == 0,正常， $ret[1] = PTID,$ret[2] = SDID
     * $ret[1] != 0, $ret[1] = error
     * 
     * @param string $id | sdid or ptid
     * @return array
     */
    public static function convertId ($id)
    {
        $verifyURL = "http://ptcom.sdo.com/common/ConvertId.aspx?uuid={$id}";
        require_once dirname(__FILE__) . '/../http/Request.php';
        $message = '';
        $content = Request::getContent($verifyURL, $message);
        if ($content === FALSE) {
            # 出错
            return FALSE;
        } else {
            # 正常
            $info = explode('^$^', $content);
            return $info;
        }
    }
}
